package com.wang.controller;

import com.google.code.kaptcha.Producer;
import com.wang.service.AddressService;
import com.wang.service.NotifyService;
import com.wang.enums.BizCodeEnum;
import com.wang.enums.SendCodeEnum;
import com.wang.util.CommonUtil;
import com.wang.util.JsonData;
import com.wang.vo.AddressVO;
import com.wang.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Api(tags = "通知模块")
@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {
    @Autowired
    private Producer captchaProducer;

    /**
     * 临时使用10分钟，方便测试
     */
    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private NotifyService notifyService;

    /**
     * 获取图形验证码
     * @param request
     * @param response
     */
    @ApiOperation("获取图形验证码")
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String captchaText = captchaProducer.createText();
        log.info("图形验证码：" + captchaText);

        // 将验证码保存到redis中(存储)
        redisTemplate.opsForValue().set(getCaptchaKey(request),captchaText,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);


        BufferedImage captchaImage = captchaProducer.createImage(captchaText);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(captchaImage, "jpg", outputStream);
            outputStream.flush();
            outputStream.flush();
        } catch (Exception e) {
            log.error("获取图形验证码异常！", e);
        }
    }

    /**
     * 获取缓存的key
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request){
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");

        String key = "user-service:captcha:"+CommonUtil.MD5(ip+userAgent);
        log.info("ip={"+ip+"}");
        log.info("userAgent={"+userAgent+"}");
        return key;
    }


    /**
     * 支持手机号、邮箱发送验证码
     * @return
     */
    @ApiOperation("发送验证码")
    @GetMapping("/send_code")
    private JsonData sendCode(@ApiParam("收信人") @RequestParam(value = "to", required = true)String to,
                              @ApiParam("图形验证码") @RequestParam(value = "captcha", required = true)String  captcha,
                              HttpServletRequest request){
        String key = getCaptchaKey(request);
        System.out.println(key);
        String cacheCaptcha = (String) redisTemplate.opsForValue().get(key);

        if(captcha != null && cacheCaptcha != null && cacheCaptcha.equalsIgnoreCase(captcha)){
            JsonData jsonData = notifyService.sendCode(SendCodeEnum.USER_REGISTER,to);
            redisTemplate.delete(key);
            return jsonData;
        }else{
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA);
        }
    }

}
